//
// Created by steven on 2017/2/27.
// Copyright (c) 2017 steven. All rights reserved.
//

#import "GMSubUserDetailViewController.h"
#import "GMSubUserModel.h"
#import "GMSubUserDataController.h"
#import <MBProgressHUD/MBProgressHUD.h>

@interface GMSubUserDetailViewController()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UILabel *hintLabel;
@property (nonatomic, strong) XLFormDescriptor * form;
@property (nonatomic, strong) XLFormSectionDescriptor * section;

@property (nonatomic, strong)UIBarButtonItem *editBarButtonItem;
@property (nonatomic, strong)UIBarButtonItem *cancelBarButtonItem;
@property (nonatomic, assign)BOOL editMode;

@property (nonatomic, strong)GMSubUserDataController *subUserDataController;

@end

@implementation GMSubUserDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.editMode = NO;
    self.subUserDataController = [[GMSubUserDataController alloc] init];

    [self initializeForm];
    [self setupMainView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.editBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editBarButtonItemPressed)];
    self.cancelBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarButtonItemPressed)];

    self.navigationItem.rightBarButtonItem = self.editBarButtonItem;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    self.form.disabled = YES;
    [self.tableView reloadData];
}

- (void)initializeForm {
    XLFormRowDescriptor * row;

    self.form = [XLFormDescriptor formDescriptor];

    // First section
    self.section = [XLFormSectionDescriptor formSectionWithTitle:@"子账户信息"];
    [self.form addFormSection:self.section];

    // username
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"account" rowType:XLFormRowDescriptorTypeText title:@"用户名"];
    row.value = self.subUserModel.account;
    row.cellConfig[@"textField.textColor"] = [UIColor grayColor];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);
    row.disabled = @YES;
    [self.section addFormRow:row];

    // phone
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"password" rowType:XLFormRowDescriptorTypeText title:@"密码"];
    row.value = self.subUserModel.password;
    row.cellConfig[@"textField.textColor"] = [UIColor grayColor];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);
    [self.section addFormRow:row];

    // guard sn
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"name" rowType:XLFormRowDescriptorTypeText title:@"姓名"];
    row.value = self.subUserModel.name;
    row.cellConfig[@"textField.textColor"] = [UIColor grayColor];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);
    [self.section addFormRow:row];

    // guard sn
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"phone" rowType:XLFormRowDescriptorTypeText title:@"手机号"];
    row.value = self.subUserModel.phoneNumber;
    row.cellConfig[@"textField.textColor"] = [UIColor grayColor];
    row.cellConfig[@"textField.textAlignment"] = @(NSTextAlignmentRight);
    [self.section addFormRow:row];

    self.form = self.form;
}

- (void)setupMainView {
    self.navigationItem.title = @"子账户信息";
}

#pragma mark - editBarButtonItemPressed
- (void)editBarButtonItemPressed {
    if (self.editMode) {
        // save action
        NSDictionary *formDict = [self.form formValues];
        NSDictionary *params = @{@"id": [NSString stringWithFormat:@"%ld", (long)self.subUserModel.id],
                @"name":formDict[@"name"],
                @"phone_number":formDict[@"phone"],
                @"password":formDict[@"password"]};

        [self.subUserDataController updateSubUserWithParams:params callback:^(NSString *error) {
            if (error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self renderSuccessView];
                });
            } else {
                [self showAlertMessage:error];
            }
        }];
    } else {
        self.editMode = YES;
        self.editBarButtonItem.title = @"保存";
        self.navigationItem.rightBarButtonItems = @[self.editBarButtonItem, self.cancelBarButtonItem];
        self.form.disabled = NO;
        [self.form formRowWithTag:@"account"].disabled = @YES;
        [self.tableView reloadData];
    }

}

#pragma mark - cancel barbutton item pressed
- (void)cancelBarButtonItemPressed {
    self.editMode = NO;
    self.editBarButtonItem.title = @"编辑";
    self.navigationItem.rightBarButtonItems = @[self.editBarButtonItem];

    [self.form formRowWithTag:@"account"].value = self.subUserModel.account;
    [self.form formRowWithTag:@"name"].value = self.subUserModel.name;
    [self.form formRowWithTag:@"phone"].value = self.subUserModel.phoneNumber;
    [self.form formRowWithTag:@"password"].value = self.subUserModel.password;
    self.form.disabled = YES;
    [self.tableView reloadData];
}

#pragma mark - render success view
- (void)renderSuccessView {
    self.editMode = NO;
    self.editBarButtonItem.title = @"编辑";
    self.navigationItem.rightBarButtonItems = @[self.editBarButtonItem];

    NSDictionary *userDict = self.subUserDataController.response[@"data"];

    [self.form formRowWithTag:@"account"].value = userDict[@"account"];
    [self.form formRowWithTag:@"name"].value = userDict[@"name"];
    [self.form formRowWithTag:@"phone"].value = userDict[@"phoneNumber"];
    [self.form formRowWithTag:@"password"].value = userDict[@"password"];

    self.form.disabled = YES;
    [self.tableView reloadData];

    [self showAlertMessage:@"保存成功"];
}

- (UILabel *)hintLabel {
    if (!_hintLabel) {
        _hintLabel = [[UILabel alloc] init];
        _hintLabel.textColor = HINT_COLOR;
        _hintLabel.text = @"请妥善保管账户信息，以防泄漏。";
    }
    return _hintLabel;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] init];
    if (![footerView viewWithTag:1001]) {
        UILabel *footerLabel = [[UILabel alloc] init];
        footerLabel.textColor = HINT_COLOR;
        footerLabel.text = @"请妥善保管账户信息，以防泄漏。";
        [footerView addSubview:footerLabel];
        [footerLabel autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
        [footerLabel autoAlignAxisToSuperviewAxis:ALAxisVertical];
    }

    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 128;
}

#pragma mark - show alert message
- (void)showAlertMessage:(NSString *)msg {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = msg;
    // Configure for text only and offset down
    hud.margin = 10.f;
    hud.yOffset = Main_Screen_Height/2-98;
    hud.removeFromSuperViewOnHide = YES;

    [hud hide:YES afterDelay:MESSAGE_SHOW_TIME];
}

@end